package a1_p04_jw_kw.graph;

import java.util.Set;

import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultWeightedEdge;

import a1_p04_jw_kw.struct.GraphSetup;
import a1_p04_jw_kw.struct.Node;

public class GraphPersistencer {
	GraphSetup gs;
	Graph<Node, DefaultWeightedEdge> g;

	public GraphPersistencer(GraphSetup gs, Graph<Node, DefaultWeightedEdge> g) {
		this.gs = gs;
		this.g = g;

	}

	public void saveGraph() {
		String text;

		// format the output

		// direct or undirected
		if (gs.isDirected) {
			text = "#gerichtet\n";

		} else {
			text = "#ungerichtet\n";
		}

		// attributed, weighted or both
		if (gs.isAttributed && gs.isWeighted) {
			text += "#attributiert,gewichtet\n";

		} else if (gs.isWeighted) {
			text += "#gewichtet\n";

		} else if (gs.isAttributed) {
			text += "#attributiert\n";

		}

		// edges
		Set<DefaultWeightedEdge> edges = g.edgeSet();

		for (DefaultWeightedEdge edge : edges) {
			if (gs.isAttributed && gs.isWeighted) {
				text += g.getEdgeSource(edge).name + ","
						+ String.valueOf(g.getEdgeSource(edge).attribute) + ","
						+ g.getEdgeTarget(edge).name + ","
						+ String.valueOf(g.getEdgeTarget(edge).attribute) + ","
						+ g.getEdgeWeight(edge) + "\n";
				
			} else if (!gs.isAttributed && gs.isWeighted) {
				text += g.getEdgeSource(edge).name + ","
						+ g.getEdgeTarget(edge).name + ","
						+ g.getEdgeWeight(edge) + "\n";
				
			} else if (gs.isAttributed && !gs.isWeighted) {
				text += g.getEdgeSource(edge).name + ","
						+ String.valueOf(g.getEdgeSource(edge).attribute) + ","
						+ g.getEdgeTarget(edge).name + ","
						+ String.valueOf(g.getEdgeTarget(edge).attribute) + "\n";
				
			} else if (!gs.isAttributed && !gs.isWeighted) {
				text += g.getEdgeSource(edge).name + ","
						+ g.getEdgeTarget(edge).name + "\n";
				
			}
		}

		GraphIO io = new GraphIO();
		io.saveToFile(text, "../out.gka");
	}

}
